package cc.grapevine.vps.http;

import java.util.LinkedList;

public class HttpManager
{
	private static HttpManager manager;
	private SendThread m_Send;
	private boolean m_isStart;
	private LinkedList<HttpRequestVps> m_SendQuene;
	private Object lock;
	private boolean isNeedWakeUp;
	private HttpListen m_listen;

	public void setListen(HttpListen listen)
	{
		m_listen = listen;
	}

	public interface HttpListen
	{
		void httpResponse(HttpResponseVps responseVps);
	}

	private HttpManager()
	{
		m_SendQuene = new LinkedList<HttpRequestVps>();
		lock = new Object();

	}

	public static HttpManager getInstence()
	{
		if (null == manager)
		{
			manager = new HttpManager();
		}
		return manager;
	}

	public void start()
	{
		m_isStart = true;
		m_Send = new SendThread();
		m_Send.start();
	}

	public void stop()
	{

		m_isStart = false;
		if (null != m_Send)
		{
			m_Send.interrupt();
			m_Send = null;
		}
		if (null != m_SendQuene)
		{
			m_SendQuene.clear();
			m_SendQuene = null;
		}
		manager = null;
	}

	int count = 0;

	public void addRequest(HttpRequestVps requestVps)
	{
		synchronized (m_SendQuene)
		{

			m_SendQuene.add(requestVps);
		}

		if (isNeedWakeUp)
		{
			synchronized (lock)
			{
				lock.notifyAll();
			}
		}
	}

	private class SendThread extends Thread
	{
		@Override
		public void run()
		{

			HttpClient client = new HttpClient();

			while (m_isStart)
			{
				HttpRequestVps request = null;
				synchronized (m_SendQuene)
				{
					request = m_SendQuene.poll();
				}

				if (null != request)
				{
					HttpResponseVps responseVps = new HttpResponseVps();

					responseVps.action = request.getAction();
					responseVps.vpsData = request;
					try
					{
						responseVps.content = client.getMethod(request.getUrl());
					}
					catch (Exception e)
					{
						responseVps.httpError = true;
						e.printStackTrace();
					}
					m_listen.httpResponse(responseVps);
				}
				else
				{
					try
					{
						synchronized (lock)
						{
							isNeedWakeUp = true;
							lock.wait();
							isNeedWakeUp = false;
						}
					}
					catch (InterruptedException e)
					{
					}
				}

			}
		}
	}

}